package Controller

import (
	"backend/Dao"
	"backend/Service/dbService"
	"github.com/gin-gonic/gin"
	"strconv"
)

type DiscussContentController struct {
}
type reqAddComments struct {
	TopicId int `json:"topicId,string"`
	Content string
}

//
// AddComments
// @Description: 新增评论
// @author MaTaoXun 2022-01-15 17:03:57
// @return gin.HandlerFunc
//
func (this DiscussContentController) AddComments(c *gin.Context) {
	var BodyData reqAddComments
	c.BindJSON(&BodyData)
	get, _ := c.Get("userId")
	id, _ := strconv.Atoi(get.(string))
	var student Dao.Student
	dbService.DbConn.Where("id = ?", id).Select("stu_name").Find(&student)
	dbService.DbConn.Create(&Dao.ContentsDiscussion{
		Model:       Dao.GetModel(),
		Content:     BodyData.Content,
		SpeakerId:   id,
		SpeakerName: student.StuName,
		TopicId:     BodyData.TopicId,
	})

	c.String(200, "ok")
}

type reqAddRep struct {
	RepSpeakerName       string
	ContentsDiscussionId int `json:"contentsDiscussionId,string"`
	RepRepId             int `json:"RepRepId,string"`
	Content              string
}

//
// AddRep
// @Description: 新增回复
// @author MaTaoXun 2022-01-15 17:07:52
// @return gin.HandlerFunc
//
func (this DiscussContentController) AddRep(c *gin.Context) {

	var BodyData reqAddRep
	c.BindJSON(&BodyData)
	get, _ := c.Get("userId")
	id, _ := strconv.Atoi(get.(string))
	var studentSpk Dao.Student
	dbService.DbConn.Where("id = ?", id).Select("stu_name").Find(&studentSpk)
	dbService.DbConn.Create(&Dao.RepContentDiscussion{
		Model:                Dao.GetModel(),
		ContentsDiscussionId: BodyData.ContentsDiscussionId,
		RepRepId:             BodyData.RepRepId,
		RepRepName:           BodyData.RepSpeakerName,
		SpeakerId:            id,
		SpeakerName:          studentSpk.StuName,
		Content:              BodyData.Content,
	})

	c.String(200, "ok")
}

type resPageComments struct {
	CommentList []resPageCommentsComment
	Count       int
}
type resPageCommentsComment struct {
	ContentDiscussion Dao.ContentsDiscussion
	RepList           []Dao.RepContentDiscussion
	RepCount          int
}

// PageComments
// @Summary 分页获取评论
// @Description 分页获取评论
// @Tags 讨论相关接口
// @Accept application/json
// @Produce application/json
// @Param tk header string false "token"
// @Param pageSize query string false "分页大小"
// @Param page query string false "页码"
// @Param TopicId query string false "讨论话题id"
// @Success 200
// @Router /PageComments [get]
func (this DiscussContentController) PageComments(c *gin.Context) {
	var CommentList []resPageCommentsComment
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	page, _ := strconv.Atoi(c.Query("page"))
	var contents []Dao.ContentsDiscussion
	// 获取该标题下的分页评论
	dbService.DbConn.Where("topic_id = ?", c.Query("TopicId")).Order("id desc").Limit(pageSize).Offset((page - 1) * pageSize).Find(&contents)
	// 所有评论的id列表
	contentsIds := make([]uint, 0)
	for _, content := range contents {
		contentsIds = append(contentsIds, content.ID)
	}
	//获取每条评论的回复数量
	var DisRepCount []map[string]interface{}
	dbService.DbConn.Model(&Dao.RepContentDiscussion{}).Select("COUNT(*) as count", "contents_discussion_id").Group("contents_discussion_id").Find(&DisRepCount)
	//获取所有评论的前5条
	var reps []Dao.RepContentDiscussion
	dbService.DbConn.Raw("select * from rep_content_discussion a where (select COUNT(*) from "+
		"rep_content_discussion b where a.contents_discussion_id=b.contents_discussion_id and a.id<b.id)<5 and a.contents_discussion_id in ? ORDER BY a.id desc;", contentsIds).Scan(&reps)

	// key:评论的id
	disMapRepList := make(map[int]*struct {
		repList  []Dao.RepContentDiscussion // 回复的列表
		repCount int                        // 回复的数目
	})
	// 初始化map
	for _, disRep := range DisRepCount {
		countI, _ := strconv.Atoi(string(disRep["count"].([]byte)))
		disMapRepList[disRep["contents_discussion_id"].(int)] = &struct {
			repList  []Dao.RepContentDiscussion
			repCount int
		}{repList: make([]Dao.RepContentDiscussion, 0), repCount: countI}
	}
	for _, rep := range reps {
		disMapRepList[rep.ContentsDiscussionId].repList = append(disMapRepList[rep.ContentsDiscussionId].repList, rep)
	}

	for _, content := range contents {
		repInfo, exist := disMapRepList[int(content.ID)]
		if exist {
			CommentList = append(CommentList, resPageCommentsComment{
				ContentDiscussion: content,
				RepList:           repInfo.repList,
				RepCount:          repInfo.repCount,
			})
		} else {
			CommentList = append(CommentList, resPageCommentsComment{
				ContentDiscussion: content,
				RepList:           make([]Dao.RepContentDiscussion, 0),
				RepCount:          0,
			})
		}

	}
	var count int64
	dbService.DbConn.Model(&Dao.ContentsDiscussion{}).Where("topic_id = ?", c.Query("TopicId")).Count(&count)
	rs := resPageComments{CommentList: CommentList, Count: int(count)}
	c.JSON(200, rs)
}

// PageRepListByCommentId
// @Summary 根据评论id获取回复列表(滚动条,每次获取该回复id之前的5条)
// @Description 根据评论id获取回复列表(滚动条,每次获取该回复id之前的5条)
// @Tags 讨论相关接口
// @Accept application/json
// @Produce application/json
// @Param tk header string false "token"
// @Param repId query string false "回复id"
// @Success 200
// @Router /PageRepListByCommentId [get]
func (this DiscussContentController) PageRepListByCommentId(c *gin.Context) {
	repIdI, _ := strconv.Atoi(c.Query("repId"))
	var repList []Dao.RepContentDiscussion
	dbService.DbConn.Raw("select *"+
		" from rep_content_discussion "+
		"where contents_discussion_id = "+
		"      (select contents_discussion_id from rep_content_discussion where id = ?) "+
		"and id < ? order by id desc limit 5;", repIdI, repIdI).Scan(&repList)
	c.JSON(200, repList)
}
